<?php

namespace App\Http\Controller\AdminPort;

use App\Model\RoleModel;
use App\Service\RoleService;
use Hyperf\Di\Annotation\Inject;


/**
 *  角色管理
 * @package App\Http\Controller\AdminPort
 */
class Role
{
    #[Inject]
    protected RoleService $roleService;

    /**
     * 获取详情
     * @return string[]
     * @throws \Exception
     */
    public function get()
    {
        RoleModel::validateColumn(
            [],
            [
                RoleModel::C_ID,
            ]
        );

        $role = $this->roleService->getInfo(authUser()->companyId, authUser()->type, I(RoleModel::C_ID));
        return getResponseData('', $role);
    }

    /**
     * 获取分页列表
     * @return string[]
     */
    public function getListPage()
    {
        RoleModel::validateColumn(
            [
                RoleModel::C_NAME,
                RoleModel::C_STATUS
            ]
        );

        $params = [
            RoleModel::C_NAME => I(RoleModel::C_NAME),
            RoleModel::C_STATUS => I(RoleModel::C_STATUS),
            RoleModel::C_COMPANY_ID => authUser()->companyId
        ];

        $data = $this->roleService->getListByPage($params, 15);
        return getResponseData('', $data);
    }

    /**
     * 创建角色
     */
    public function create()
    {
        return $this->saveRole(true);
    }

    /**
     * 修改角色信息
     * @return array
     */
    public function update()
    {
        return $this->saveRole(false);
    }

    /**
     * 创建和编辑角色信息
     * @param bool $isCreate
     * @return array
     */
    protected function saveRole(bool $isCreate = false)
    {
        $required = [
            RoleModel::C_NAME,
            RoleModel::C_STATUS
        ];

        if ( ! $isCreate) {
            $required[] = RoleModel::C_ID;
        }

        $role = RoleModel::validateColumn([
                    RoleModel::C_PERMISSIONS,
                ],
                $required,
                true
        );

        $this->roleService->save(authUser()->companyId, authUser()->type, $role);
        return getResponseData('保存成功');
    }

    /**
     * 删除
     * @return string[]
     */
    public function delete()
    {
        RoleModel::validateColumn([], [RoleModel::C_ID]);
        $this->roleService->delete(authUser()->companyId, I(RoleModel::C_ID));
        return getResponseData('删除成功');
    }
}
